import BaseModal, { ModalFC } from '@/components/base/BaseModal';
import BaseTree from '@/components/base/BaseTree';
import { useRequest } from '@/utils/request';
import { message, Spin, Transfer } from 'antd';
import { difference } from 'lodash-es';
import { useRef, useState } from 'react';
import { getRadarTreeListByRadarId, getRadarTreeNoDoList, saveRadarTree } from '../api';

const generateTree = (treeNodes: any[] = [], checkedKeys: string[] = []) => {
  const checked: Record<string, unknown>[] = [];
  const unChecked: Record<string, unknown>[] = [];
  treeNodes.forEach(({ children, ...props }) => {
    if (children && children.length > 0) {
      const childs = generateTree(children, checkedKeys);
      if (childs.unChecked.length > 0) {
        unChecked.push({
          ...props,
          children: childs.unChecked
        });
      }
      if (childs.checked.length > 0) {
        checked.push({
          ...props,
          children: childs.checked
        });
      }
    } else if (checkedKeys.includes(props.allId)) {
      checked.push({ ...props, children: [] });
    } else {
      unChecked.push({ ...props, children: [] });
    }
  });
  return {
    checked,
    unChecked
  };
};
const formatKeys = (data: Record<string, any>[], parentIds = '') => {
  const ids: string[] = [];
  data.forEach((item) => {
    const prefix = parentIds !== '' ? `${parentIds}-` : '';
    const id = `${prefix}${item.id}`;
    if (item.children && item.children.length > 0) {
      ids.push(...formatKeys(item.children, id));
    }
    ids.push(id);
  });
  return ids;
};
const EditStructureModal: ModalFC<{ id: string }> = ({ id, ...props }) => {
  const tree = useRequest(getRadarTreeNoDoList);
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const oldRadarTreeIds = useRef<string[]>([]);
  useRequest(getRadarTreeListByRadarId, {
    defaultParams: [id],
    onSuccess(data) {
      const ids = formatKeys(data || []);
      oldRadarTreeIds.current = ids;
      setTargetKeys(ids);
    }
  });
  const save = useRequest(saveRadarTree, {
    manual: true,
    onSuccess() {
      props.onSuccess && props.onSuccess();
      props.onCancel();
    }
  });
  const transferDataSource: any[] = [];
  const flatten = (list: Record<string, any>[] = [], parentIds: string[]) => {
    list.forEach((item: any) => {
      item.allId = `${parentIds.join('-')}-${item.id}`;
      transferDataSource.push(item);
      if (item.children) {
        flatten(item.children, [...parentIds, item.id]);
      }
    });
  };
  flatten(tree.data, [id]);
  const { checked, unChecked } = generateTree(tree.data, targetKeys);
  return (
    <BaseModal
      title='编辑雷达树'
      onOk={() => {
        const upKeys: string[] = [];
        targetKeys.forEach((key) => {
          const keySplit = key.split('-');
          keySplit.reduce((prev, current) => {
            const upKey = prev === '' ? current : `${prev}-${current}`;
            upKeys.push(upKey);
            return upKey;
          }, '');
        });
        const createIds = [...new Set(upKeys)];
        const oldIds = oldRadarTreeIds.current;
        const deleteIds: string[] = [];
        oldIds.forEach((i) => {
          const index = createIds.findIndex((id) => i === id);
          if (index !== -1) {
            createIds.splice(index, 1);
          } else {
            deleteIds.push(i);
          }
        });
        if (createIds.length === 0 && deleteIds.length === 0) {
          message.warning('当前暂无需要新增或删除的节点');
        } else {
          save.run({ createIds, deleteIds });
        }
      }}
      okButtonProps={{ disabled: tree.loading, loading: save.loading }}
      okText='提交'
      {...props}
    >
      <Spin spinning={tree.loading}>
        <Transfer
          onChange={(t) => {
            setTargetKeys([...new Set(t)]);
          }}
          rowKey={(record) => record.allId}
          targetKeys={targetKeys}
          dataSource={transferDataSource}
          className='tree-transfer'
          render={(item) => item.title}
          showSelectAll={false}
          selectAllLabels={['未绑定雷达树', '已绑定雷达树']}
          // titles={['未绑定雷达树', '已绑定雷达树']}
        >
          {({ direction, onItemSelectAll, selectedKeys }) => {
            return (
              <BaseTree
                blockNode
                checkable
                defaultExpandAll
                height={400}
                bindProps={{ key: 'allId', value: 'allId', title: 'name' }}
                treeData={direction === 'left' ? unChecked : checked}
                checkedKeys={selectedKeys}
                selectedKeys={selectedKeys}
                onCheck={(checkedKeys) => {
                  const noHasKeys = difference(selectedKeys, checkedKeys as any[]);
                  onItemSelectAll(noHasKeys, false);
                  onItemSelectAll(checkedKeys as any[], true);
                }}
                onSelect={(selected) => {
                  const noHasKeys = difference(selectedKeys, selected as any[]);
                  onItemSelectAll(noHasKeys, false);
                  onItemSelectAll(selected as any[], true);
                }}
              />
            );
          }}
        </Transfer>
      </Spin>
    </BaseModal>
  );
};

export default EditStructureModal;
